package com.zhkj.txg.module.mine.ui

import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.home.entity.ListEntity
import com.zhkj.txg.module.member.ui.MemberWithdrawListActivity
import com.zhkj.txg.module.mine.adapter.RechargeAmountAdapter
import com.zhkj.txg.module.mine.vm.BalanceViewModel
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.ui.OnItemClickListener
import com.zhkj.txg.module.order.ui.SimplePopupWindow
import com.zhkj.txg.utils.*
import kotlinx.android.synthetic.main.activity_balance_opration.*
import java.math.BigDecimal

class BalanceOperationActivity : ViewModelActivity<BalanceViewModel>() {

    companion object {
        private val TYPE_RECHARGE = 0
        private val TYPE_WITHDRAW = 1
        private val TYPE: String = "type"

        // 充值
        fun startRecharge(activity: Activity) {
            val intent = Intent(activity, BalanceOperationActivity::class.java)
                .putExtra(TYPE, TYPE_RECHARGE)
            activity.startActivity(intent)
        }

        // 提现
        fun startWithdraw(activity: Activity) {
            val intent = Intent(activity, BalanceOperationActivity::class.java)
                .putExtra(TYPE, TYPE_WITHDRAW)
            activity.startActivity(intent)
        }
    }

    var listEntity: ListEntity? = null
    private val rechargeAmountAdapter: RechargeAmountAdapter by lazy {
        RechargeAmountAdapter {
            this.listEntity = it
        }
    }

    private val requestCodeBind = 1090

    override fun setViewModel(): BalanceViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleBalanceOperation
    override val layoutResId: Int = R.layout.activity_balance_opration

    override fun initUI() {

        with(tvRechargeAmount) {
            layoutManager = GridLayoutManager(context, 3).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
//                initialPrefetchItemCount = 6
            }
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(this@BalanceOperationActivity, 10),
                    ScreenUtil.dip(this@BalanceOperationActivity, 10)
                )
            )
            adapter = rechargeAmountAdapter
        }

        viewWxPay.isSelected = true
        viewAliPay.setOnClickListener {
            if (intent.getIntExtra(TYPE, TYPE_RECHARGE) == TYPE_WITHDRAW) {
                viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                    if (!it.isBindAliPay) return@setOnClickListener
                }
            }
            viewAliPay.isSelected = true
            viewWxPay.isSelected = false
        }
        viewWxPay.setOnClickListener {
            if (intent.getIntExtra(TYPE, TYPE_RECHARGE) == TYPE_WITHDRAW) {
                viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                    if (!it.isBindWeChat) return@setOnClickListener
                }
            }
            viewAliPay.isSelected = false
            viewWxPay.isSelected = true
        }
        // 判断输入框金额大小是否大于余额
//        etBalanceAmount.addTextChangedListener(TextWatcherWrapper { origin ->
//            if (!origin.isNullOrEmpty()) {
//                // 第一步，先格式化数据格式
//                if (origin.contains('.')) {
//                    val index = origin.indexOf('.')
//                    if (index == 0) origin.insert(0, "0") // 金额以'.'开头
//                    else if (index < origin.lastIndex - 2)// 金额小数大于两位 例如:11.2236
//                        origin.delete(index + 3, origin.length)
//                }
//                if (intent.getIntExtra(TYPE, TYPE_RECHARGE) == TYPE_WITHDRAW)
//                    viewModel.balanceLiveData.value?.response?.data?.userInfo?.let {
//                        // 第二步，再比较金额大小
//                        val balance = BigDecimal(it.money)
//                        val currentAmount = BigDecimal(origin.toString())
//                        if (currentAmount > balance) {// 输入金额大于余额
//                            origin.replace(0, origin.length, balance.toPlainString())
//                            etBalanceAmount.setSelection(etBalanceAmount.text?.length ?: 0)
//                        }
//                    }
//            }
//        })
        // 确认按钮点击监听
        btnBalanceConfirm.setOnClickListener {
            if (intent.getIntExtra(TYPE, TYPE_RECHARGE) == TYPE_RECHARGE) { // 发起支付
                viewModel.recharge(
                    AccountManager.getToken(),
                    listEntity?.payPrice.toString(),
                    if (viewAliPay.isSelected) OrderPayEntity.TYPE_ALIPAY else OrderPayEntity.TYPE_WECHAT,
                    CustomApplication.getShopId().toString()
                )
            } else {// 提现
//                viewModel.withdrawConfigLiveData.value?.response?.data?.let { entity ->
//                    if (entity.canWithdraw != "1") { // 提现功能是否开启
//                        toast(getString(R.string.withdraw_close))
//                        return@setOnClickListener
//                    }
//                    // 判断提现金额是否在区间之内
//                    val withdrawAmount = BigDecimal(etBalanceAmount.text.toString())
//                    val minWithdraw = BigDecimal(entity.minWithdrawAmount)
//                    if (minWithdraw > BigDecimal(0) && minWithdraw > withdrawAmount) {
//                        toast(String.format(getString(R.string.withdraw_too_small), entity.minWithdrawAmount))
//                        return@setOnClickListener
//                    }
//                    val maxWithdraw = BigDecimal(entity.maxServiceMoney)
//                    if (maxWithdraw > BigDecimal(0) && maxWithdraw < withdrawAmount) {
//                        toast(String.format(getString(R.string.withdraw_too_large), entity.maxWithdrawAmount))
//                        return@setOnClickListener
//                    }
//                    // 判断选中的支付方式是否有绑定
//                    val unbind =
//                        (viewAliPay.isSelected && viewModel.withdrawConfigLiveData.value?.response?.data?.isBindAliPay == false)
//                                || (viewWxPay.isSelected && viewModel.withdrawConfigLiveData.value?.response?.data?.isBindWeChat == false)
//                    if (unbind) {
//                        toast(getString(R.string.bind_hint))
//                        return@setOnClickListener
//                    }
//                    SimplePopupWindow(this).setTitle(
//                        getString(
//                            if (viewAliPay.isSelected) R.string.withdraw_ali_hint else R.string.withdraw_wx_hint
//                        )
//                    ).setContent(
//                        getString(
//                            if (viewAliPay.isSelected) R.string.withdraw_ali_hint_content
//                            else R.string.withdraw_wx_hint_content
//                        )
//                    ).setConfirmCallback(object : OnItemClickListener {
//                        override fun onClick(popupWindow: SimplePopupWindow) {
//                            viewModel.withdraw(
//                                withdrawAmount.toPlainString(),
//                                if (viewAliPay.isSelected) OrderPayEntity.TYPE_ALIPAY else OrderPayEntity.TYPE_WECHAT,
//                                entity.withdrawToken
//                            )
//                            popupWindow.dismiss()
//                        }
//                    }).showPopupWindow()
//                }
            }
        }
        tvRechargeShuoming.setOnClickListener {
            RechargeActivity.openCZ(this,"充值说明","https://www.txemart.com/api/article/recharge")
        }
    }

    override fun initData() {
        viewModel.getRechargeList()

        val type = intent.getIntExtra(TYPE, TYPE_RECHARGE)
        with(titleBalanceOperation) {
            setTitleTextContent(
                getString(if (type == TYPE_RECHARGE) R.string.balance_recharge else R.string.balance_withdraw_title)
            )
            showRight(type == TYPE_WITHDRAW)
            if (type == TYPE_WITHDRAW) setRightTextContent(getString(R.string.withdraw_history))
                .setRightClickListener(View.OnClickListener {
                    MemberWithdrawListActivity.user(this@BalanceOperationActivity)
                })
        }
//        tvBalanceAmountStr.text =
//            getString(if (type == TYPE_RECHARGE) R.string.balance_now else R.string.balance_withdraw_now)
//        tvBalanceAmountOperationStr.text =
//            getString(if (type == TYPE_RECHARGE) R.string.recharge_amount else R.string.withdraw_amount)
//        etBalanceAmount.hint =
//            getString(if (type == TYPE_RECHARGE) R.string.recharge_amount_hint else R.string.withdraw_amount_hint)
//        tvBalanceOperationStr.text =
//            getString(if (type == TYPE_RECHARGE) R.string.select_pay_type else R.string.select_withdraw_type)
        tvBalanceAli.text =
            getString(if (type == TYPE_RECHARGE) R.string.ali_pay else R.string.ali_withdraw)
        tvBalanceWx.text =
            getString(if (type == TYPE_RECHARGE) R.string.wx_pay else R.string.wx_withdraw)
//        btnBalanceConfirm.text =
//            getString(if (type == TYPE_RECHARGE) "立即充值" else R.string.confirm_withdraw)
//        viewAliPay.isSelected = true

        // 如果是提现，先调用获取提现配置接口
        if (type == TYPE_WITHDRAW) viewModel.withdrawConfig()
        else {
            ivAliPay.visibility = View.VISIBLE
            ivWeChat.visibility = View.VISIBLE
        }
        // 获取余额
        viewModel.refreshBalance()
    }

    override fun initViewModel() {
        // 余额数据观察者
        viewModel.balanceLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.userInfo?.let {
                tvBalanceAmount.text = SpanUtil.setMoneySymbol(it.money)
            }
        })
        // 微信支付结果观察者
        viewModel.payResultSubscribe().observe(this, Observer {
            if (it.paySuccess) {
                toast(getString(R.string.pay_success))
                // 支付成功，刷新余额
                viewModel.refreshBalance()
                // 余额刷新
                RxBus.post(BalanceChangeEvent())
            } else toast(it.payDesc)
        })
        // 余额提现订单数据观察者
        viewModel.rechargeLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                when (order.payType) {
                    // 微信支付
                    OrderPayEntity.TYPE_WECHAT -> {
                        order.payInfo.let {
                            PayUtils.wxPay(this, Gson().fromJson(it, WXPayEntity::class.java))
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(this, order.payInfo, {
                        toast(getString(R.string.pay_success))
                        // 支付成功，刷新余额
                        viewModel.refreshBalance()
                        // 余额刷新
                        RxBus.post(BalanceChangeEvent())
                    }, { toast(it) })
                    else -> Unit
                }
            }
        })
        // 提现配置数据观察者
        viewModel.withdrawConfigLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
//                if (it.canWithdraw != "1") {
//                    etBalanceAmount.isEnabled = false
//                    btnBalanceConfirm.isEnabled = false
//                    toast(getString(R.string.withdraw_close))
//                    return@let
//                }
//                etBalanceAmount.hint = String.format(getString(R.string.withdraw_hint), it.minWithdrawAmount)
                // 判断支付宝是否已绑定
                if (it.isBindAliPay) {
                    ivAliPay.visibility = View.VISIBLE
                }
                // 判断微信是否已绑定
                if (it.isBindWeChat) {
                    ivWeChat.visibility = View.VISIBLE
                }
            }
        })
        // 提现结果数据观察者
        viewModel.withdrawLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                toast(response.response?.msg ?: getString(R.string.withdraw_success))
                // 提现成功，刷新余额
                viewModel.refreshBalance()
                // 余额刷新
                RxBus.post(BalanceChangeEvent())
            }
            // 重新获取提现token
            if (response.status != HttpResponseStatus.Status.START) viewModel.withdrawConfig()
        })
        // 微信授权数据观察者
        viewModel.weChatBindSubscribe().observe(this, Observer {
            if (it.success) viewModel.bindWeChat(it.code)
        })
        // 微信绑定数据观察者
        viewModel.bindWeChatLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) viewModel.withdrawConfig()
        })

        viewModel.rechargeListLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                rechargeAmountAdapter.setNewData(response.response?.data?.rechargeList)
            }
        })


        // 微信支付结果观察者
        viewModel.recharge2LiveData.observe(this, Observer { response ->

            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {

            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == requestCodeBind) {
            val account = data?.getStringExtra("data")
            if (!account.isNullOrEmpty()) viewModel.withdrawConfig()
        }
    }
}